package com.yyw.foodie.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyw.foodie.enums.OrderEnums;
import com.yyw.foodie.mapper.OrderStatusMapper;
import com.yyw.foodie.pojo.OrderStatusEntity;
import com.yyw.foodie.service.OrderStatusService;
import com.yyw.foodie.utils.DateUtil;
import com.yyw.foodie.vo.center.order.OrderStatusNumsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 订单状态表;订单的每个状态更改都需要进行记录
10：待付款  20：已付款，待发货  30：已发货，待收货（7天自动确认）  40：交易成功（此时可以评价）50：交易关闭（待付款时，用户取消 或 长时间未付款，系统识别后自动关闭）
退货/退货，此分支流程不做，所以不加入 服务实现类
 * </p>
 *
 * @author yiyw
 * @since 2021-05-22
 */
@Service
public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, OrderStatusEntity> implements OrderStatusService {

    @Autowired
    private OrderStatusMapper orderStatusMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateOrderStatus(String orderId, Integer code) {
        UpdateWrapper<OrderStatusEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(OrderStatusEntity::getOrderStatus, code)
                .set(OrderStatusEntity::getPayTime, DateUtil.getCurrentDateTime())
                .eq(OrderStatusEntity::getOrderId, orderId)
                .eq(OrderStatusEntity::getOrderStatus, OrderEnums.待付款.code);
        update(updateWrapper);
    }

    @Override
    public OrderStatusNumsVo getOrderStatusNums(String userId) {
        // 获取待支付数量
        Integer waitPayCounts = orderStatusMapper.getOrderStatusNums(userId, OrderEnums.待付款.code, null);
        // 获取代发货数量
        Integer waitDeliverCounts = orderStatusMapper.getOrderStatusNums(userId, OrderEnums.已付款待发货.code, null);
        // 获取待收货数量
        Integer waitReceiveCounts = orderStatusMapper.getOrderStatusNums(userId, OrderEnums.待收货.code, null);
        // 获取待评价数量
        Integer waitCommentCounts = orderStatusMapper.getOrderStatusNums(userId, OrderEnums.交易成功.code, true);

        // 拼接参数
        OrderStatusNumsVo numsVo = new OrderStatusNumsVo();
        numsVo.setWaitPayCounts(waitPayCounts);
        numsVo.setWaitDeliverCounts(waitDeliverCounts);
        numsVo.setWaitReceiveCounts(waitReceiveCounts);
        numsVo.setWaitCommentCounts(waitCommentCounts);

        return numsVo;
    }
}
